<?php 
namespace app\admin\controller;

use app\common\model\Badge as BadgeModel;
use app\common\model\Article;
use think\Request;

class Badge extends Base
{
	/**
	 * 标签列表
	 * @return unknown
	 */
	public function index()
	{
		$list = BadgeModel::where(['state' => 1])->select()->toArray();
		foreach ($list as &$rows) {
			$rows['article_num'] = Article::where(['badge' => $rows['id'],'state' => ['state','>','0']])->count();
		}
		$this->assign('list',json_encode($list));
		return view();
	}
	/**
	 * 添加标签
	 * @param Request $request
	 * @return unknown
	 */
	public function addBadge(Request $request)
	{
		if($request->isAjax()){
			$data = $request->post();
			try {
				$data['create_time'] = time();
				BadgeModel::create($data);
			} catch (Exception $e) {
				return $this->error($e->getMessage());
			}
			return $this->success('添加成功');
		}
		return view();
	}
	/**
	 * 删除标签
	 * @param Request $request
	 * @return unknown
	 */
	public function deleteBadge(Request $request)
	{
		$id = $request->post('id');
		try {
			BadgeModel::get($id)->save(['state' => 0]);
		} catch (Exception $e) {
			return $this->error($e->getMessage());
		}
		return $this->success('删除成功');
	}
}